#!/bin/bash
# ES Archive Docker 运行脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查 Docker 和 Docker Compose
check_dependencies() {
    print_message $BLUE "检查依赖..."
    
    if ! command -v docker &> /dev/null; then
        print_message $RED "错误: Docker 未安装"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        print_message $RED "错误: Docker Compose 未安装"
        exit 1
    fi
    
    print_message $GREEN "✓ 依赖检查通过"
}

# 创建必要的目录
create_directories() {
    print_message $BLUE "创建数据目录..."
    
    mkdir -p data/backups
    mkdir -p data/metadata
    mkdir -p data/logs
    mkdir -p config
    
    print_message $GREEN "✓ 目录创建完成"
}

# 复制环境变量文件
setup_env() {
    if [ ! -f .env ]; then
        print_message $BLUE "创建环境变量文件..."
        cp .env.docker .env
        print_message $YELLOW "请编辑 .env 文件以配置您的环境"
    fi
}

# 构建服务
build_services() {
    local mirror=${1:-aliyun}
    print_message $BLUE "构建 ES Archive 服务 (使用 $mirror 镜像源)..."

    # 设置构建环境变量
    export MIRROR_TYPE=$mirror
    export BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')

    # 如果使用自定义构建脚本
    if [ -f "./build-docker.sh" ]; then
        print_message $YELLOW "使用自定义构建脚本..."
        ./build-docker.sh -c $mirror
    else
        docker-compose build es-archive
    fi

    print_message $GREEN "✓ 服务构建完成"
}

# 启动服务
start_services() {
    print_message $BLUE "启动服务..."
    docker-compose up -d
    print_message $GREEN "✓ 服务启动完成"
}

# 等待服务就绪
wait_for_services() {
    print_message $BLUE "等待服务就绪..."
    
    # 等待 Elasticsearch
    print_message $YELLOW "等待 Elasticsearch..."
    timeout=60
    while [ $timeout -gt 0 ]; do
        if curl -s http://localhost:9200/_cluster/health >/dev/null 2>&1; then
            print_message $GREEN "✓ Elasticsearch 就绪"
            break
        fi
        sleep 2
        timeout=$((timeout-2))
    done
    
    if [ $timeout -le 0 ]; then
        print_message $RED "错误: Elasticsearch 启动超时"
        exit 1
    fi
}

# 显示服务状态
show_status() {
    print_message $BLUE "服务状态:"
    docker-compose ps
    
    print_message $BLUE "\n服务访问地址:"
    print_message $GREEN "Elasticsearch: http://localhost:9200"
    print_message $GREEN "Grafana: http://localhost:3000 (admin/admin)"
    print_message $GREEN "Prometheus: http://localhost:9090"
    print_message $GREEN "ES Archive 指标: http://localhost:8080/metrics"
    print_message $GREEN "ES Archive 健康检查: http://localhost:8081/health"
}

# 执行 ES Archive 命令
run_command() {
    local cmd="$*"
    print_message $BLUE "执行命令: $cmd"
    docker-compose exec es-archive es-archive $cmd
}

# 进入容器
enter_container() {
    print_message $BLUE "进入 ES Archive 容器..."
    docker-compose exec es-archive bash
}

# 查看日志
show_logs() {
    local service=${1:-es-archive}
    print_message $BLUE "显示 $service 日志..."
    docker-compose logs -f $service
}

# 停止服务
stop_services() {
    print_message $BLUE "停止服务..."
    docker-compose down
    print_message $GREEN "✓ 服务已停止"
}

# 清理数据
clean_data() {
    print_message $YELLOW "警告: 这将删除所有数据!"
    read -p "确认删除? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_message $BLUE "清理数据..."
        docker-compose down -v
        sudo rm -rf data/
        print_message $GREEN "✓ 数据清理完成"
    fi
}

# 显示帮助
show_help() {
    echo "ES Archive Docker 管理脚本"
    echo ""
    echo "用法: $0 [命令] [参数]"
    echo ""
    echo "命令:"
    echo "  setup     - 初始化环境（创建目录、配置文件等）"
    echo "  build     - 构建服务 [镜像源]"
    echo "  start     - 启动所有服务"
    echo "  stop      - 停止所有服务"
    echo "  restart   - 重启所有服务"
    echo "  status    - 显示服务状态"
    echo "  logs      - 显示日志 [服务名]"
    echo "  exec      - 执行 ES Archive 命令"
    echo "  shell     - 进入容器 shell"
    echo "  clean     - 清理所有数据（危险操作）"
    echo "  help      - 显示此帮助"
    echo ""
    echo "镜像源选项 (用于 build 命令):"
    echo "  aliyun    - 阿里云镜像源 (默认)"
    echo "  tencent   - 腾讯云镜像源"
    echo "  huawei    - 华为云镜像源"
    echo "  ustc      - 中科大镜像源"
    echo "  tsinghua  - 清华大学镜像源"
    echo "  default   - 官方镜像源"
    echo ""
    echo "示例:"
    echo "  $0 setup                    # 初始化环境"
    echo "  $0 build aliyun             # 使用阿里云镜像源构建"
    echo "  $0 build tencent            # 使用腾讯云镜像源构建"
    echo "  $0 start                    # 启动服务"
    echo "  $0 exec backup my-index /data/backups  # 执行备份"
    echo "  $0 logs es-archive          # 查看 ES Archive 日志"
    echo "  $0 shell                    # 进入容器"
}

# 主函数
main() {
    case "${1:-help}" in
        setup)
            check_dependencies
            create_directories
            setup_env
            print_message $GREEN "✓ 环境初始化完成"
            print_message $YELLOW "请编辑 .env 和 config/docker-config.yaml 文件"
            ;;
        build)
            check_dependencies
            build_services $2
            ;;
        start)
            check_dependencies
            start_services
            wait_for_services
            show_status
            ;;
        stop)
            stop_services
            ;;
        restart)
            stop_services
            start_services
            wait_for_services
            show_status
            ;;
        status)
            show_status
            ;;
        logs)
            show_logs $2
            ;;
        exec)
            shift
            run_command "$@"
            ;;
        shell)
            enter_container
            ;;
        clean)
            clean_data
            ;;
        help|*)
            show_help
            ;;
    esac
}

# 运行主函数
main "$@"
